package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.base.core.integration.OperationPeriodIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.SchoolNatureEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.common.vo.eduSchoolTj.EduSchoolTjKeyVO;
import com.jwsoft.manager.common.vo.eduSchoolTj.EduSchoolTjQueryVO;
import com.jwsoft.manager.common.vo.eduSchoolTj.EduSchoolTjVO;
import com.jwsoft.manager.common.vo.eduStudentEnroll.EduStudentEnrollKeyVO;
import com.jwsoft.manager.common.vo.eduStudentEnroll.MyTjSchoolVO;
import com.jwsoft.manager.core.dao.model.EduSchoolTj;
import com.jwsoft.manager.core.dao.model.EduStudentEnroll;
import com.jwsoft.manager.core.dao.model.EduStudentTj;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import com.jwsoft.manager.core.dao.service.EduSchoolTjService;
import com.jwsoft.manager.core.dao.service.EduStudentEnrollService;
import com.jwsoft.manager.core.dao.service.EduStudentTjService;
import com.jwsoft.manager.core.integration.EduSchoolTjIntegration;
import com.jwsoft.manager.core.integration.EduSystemConfigIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 家长端调剂申请参数管理业务实现类
 *
 * @author wangtao
 * @since 2022-12-20
 */
@ApiService(funcCode = "eduSchoolTj", title = "家长端调剂申请参数管理")
public class EduSchoolTjIntegrationImpl implements EduSchoolTjIntegration {

    @Autowired
    public EduSchoolTjService eduSchoolTjService;

    @Autowired
    public OperationPeriodIntegration operationPeriodIntegration;

    @Autowired
    public DictHelper dictHelper;

    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private EduStudentTjService eduStudentTjService;

    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    private EduSchoolService eduSchoolService;

    @Autowired
    private EduSystemConfigIntegration eduSystemConfigIntegration;
    @Autowired
    private DictIntegration dictIntegration;

    @Override
    @OpApi(funcCode = "eduSchoolTj0001", title = "家长端调剂申请参数管理分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduSchoolTjVO> getList(EduSchoolTjQueryVO vo) {
        if(vo.getYear()==null){
            throw new AppException("招生年度不能为空");
        }
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(20);
        }
        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAreaCode())){
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
        }else {
            areaCodeList.add(vo.getAreaCode());
        }
        if (CollectionUtils.isEmpty(areaCodeList)){
            throw new AppException("必须传入行政区划");
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduSchoolTj> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSchoolTj::getYear,vo.getYear())
                .in( EduSchoolTj::getAreaCode, areaCodeList)
                .eq(StringUtils.isNotBlank(vo.getFlag()), EduSchoolTj::getFlag, vo.getFlag())
                .eq(StringUtils.isNotBlank(vo.getFromConfigName()), EduSchoolTj::getFromConfigName, vo.getFromConfigName())
                .eq(StringUtils.isNotBlank(vo.getFromSchoolId()),EduSchoolTj::getFromSchoolId,vo.getFromSchoolId())
                .eq(StringUtils.isNotBlank(vo.getToSchoolId()),EduSchoolTj::getToSchoolId,vo.getToSchoolId()).orderByAsc(EduSchoolTj::getFromSchoolId,EduSchoolTj::getCreateTime);

        List<EduSchoolTj> list = eduSchoolTjService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSchoolTj> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSchoolTjVO> resultList = Convert.toList(EduSchoolTjVO.class, pageInfo.getList());
        // 转义数据字典值
        for (EduSchoolTjVO eduSchoolTjVO : resultList) {
            eduSchoolTjVO.setAreaCodeName(dictHelper.getAreaNameByCode(eduSchoolTjVO.getAreaCode()));
        }
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduSchoolTj0002", title = "家长端调剂申请参数管理根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduSchoolTjVO getById(EduSchoolTjKeyVO vo) {
        EduSchoolTj entity = eduSchoolTjService.getById(vo.getSchoolTjId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduSchoolTjVO result = Convert.convert(EduSchoolTjVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduSchoolTj0003", title = "家长端调剂申请参数管理保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSchoolTjVO vo) {
        if (StringUtils.isBlank(vo.getFromSchoolId())) {
            throw new AppException("调出学校不能为空");
        }
        if (StringUtils.isBlank(vo.getToSchoolId())) {
            throw new AppException("调入学校不能为空");
        }
        if (StringUtils.isBlank(vo.getFromConfigName())&&CollectionUtils.isEmpty(vo.getFromConfigNameList())) {
            throw new AppException("调出学校的招生类别不能为空");
        }
        if (vo.getFromSchoolId().equals(vo.getToSchoolId())) {
            throw new AppException("调出和调入学校不能一致");
        }
        if (vo.getYear() == null) {
            Integer year = eduHelper.thisYear();
            vo.setYear(year);
        }
        EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(vo.getFromSchoolId());
        if (eduSchoolVO == null) {
            throw new AppException("调出学校不存在");
        }
        if (StringUtils.isBlank(vo.getAreaCode())) {
            vo.setAreaCode(eduSchoolVO.getAreaCode());
        }
        EduSchoolVO toSchool = eduSchoolService.getDetail(vo.getToSchoolId());
        if (toSchool == null) {
            throw new AppException("调入学校不存在");
        }
        if (!toSchool.getSchoolCategory().equalsIgnoreCase(eduSchoolVO.getSchoolCategory())) {
            throw new AppException("调入调出学校学段不一致");
        }

    }

    @Override
    @OpApi(funcCode = "eduSchoolTj0004", title = "家长端调剂申请参数管理新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduSchoolTj0004",
            operationName = "家长端调剂申请参数管理新增",
            dataType = "schoolTjId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSchoolTjVO add(EduSchoolTjVO vo) {
        List<String> lbList=new ArrayList<>();
        if (CollectionUtils.isEmpty(vo.getFromConfigNameList())){
            lbList.add(vo.getFromConfigName());
        }else{
            lbList.addAll(vo.getFromConfigNameList());
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        for(String lb:lbList) {
            QueryWrapper<EduSchoolTj> tjQueryWrapper = new QueryWrapper<>();
            tjQueryWrapper.lambda().eq(EduSchoolTj::getYear, vo.getYear())
                    .eq(EduSchoolTj::getFromSchoolId, vo.getFromSchoolId())
                    .eq(EduSchoolTj::getFromConfigName, lb)
                    .eq(EduSchoolTj::getToSchoolId, vo.getToSchoolId());
            if (eduSchoolTjService.count(tjQueryWrapper) > 0) {
                throw new AppException("学校（" + vo.getFromSchoolName() + "）类别（" + vo.getFromConfigName() + "）调剂到学校（" + vo.getToSchoolName() + "）已存在，如有问题，请修改");
            }
            vo.setSchoolTjId(IdUtil.simpleUUID());
            EduSchoolTj entity = Convert.convert(EduSchoolTj.class, vo);
            if (StringUtils.isBlank(entity.getFlag())) {
                //新增默认有效状态
                entity.setFlag(BoolEnum.TRUE.getType());
            }
            eduSchoolTjService.save(entity);
        }
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSchoolTj0005", title = "家长端调剂申请参数管理修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduSchoolTj0005",
            operationName = "家长端调剂申请参数管理修改",
            dataType = "schoolTjId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSchoolTjVO edit(EduSchoolTjVO vo) {
        if (ObjectUtils.isEmpty(vo.getSchoolTjId())) {
            throw new AppException("家长端调剂申请参数管理主键不能为空!");
        }
        checkSave(vo);
        EduSchoolTj old= eduSchoolTjService.getById(vo.getSchoolTjId());
        if(old==null){
            throw new AppException("需要修改的数据不存在");
        }
        QueryWrapper<EduSchoolTj> tjQueryWrapper=new QueryWrapper<>();
        tjQueryWrapper.lambda().eq(EduSchoolTj::getYear,vo.getYear())
                .ne(EduSchoolTj::getSchoolTjId,vo.getSchoolTjId())
                .eq(EduSchoolTj::getFromSchoolId,vo.getFromSchoolId())
                .eq(EduSchoolTj::getFromConfigName, vo.getFromConfigName())
                .eq(EduSchoolTj::getToSchoolId,vo.getToSchoolId());
        if(eduSchoolTjService.count(tjQueryWrapper)>0){
            throw new AppException("学校（" + vo.getFromSchoolName() + "）类别（" + vo.getFromConfigName() + "）调剂到学校（" + vo.getToSchoolName() + "），不能重复");
        }
        EduSchoolTj entity = Convert.convert(EduSchoolTj.class, vo);
        eduSchoolTjService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSchoolTj0006", title = "家长端调剂申请参数管理根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduSchoolTj0006",
            operationName = "家长端调剂申请参数管理删除",
            dataType = "schoolTjId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSchoolTjKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getSchoolTjId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSchoolTj entity = eduSchoolTjService.getById(vo.getSchoolTjId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduSchoolTjService.removeById(vo.getSchoolTjId());
    }


    @Override
    @OpApi(funcCode = "eduSchoolTj0009", title = "家长端根据报名id获取可调剂学校列表", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public List<MyTjSchoolVO> getByEnrollStudentId(EduStudentEnrollKeyVO vo) {
        if (StringUtils.isBlank(vo.getStudentEnrollId())) {
            throw new AppException("报名id不能为空");
        }
        EduStudentEnroll eduStudentEnroll = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (eduStudentEnroll == null) {
            throw new AppException("未找到报名的数据");
        }
        if (!SchoolNatureEnum.gb.getType().equalsIgnoreCase(eduStudentEnroll.getSchoolNature())) {
            throw new AppException("只有公办学校才能申请调剂");
        }
        EduOperationCacheQueryVO queryVO = new EduOperationCacheQueryVO();
        queryVO.setOperating("YW059");
        queryVO.setAreaCode(eduStudentEnroll.getAreaCode());
        queryVO.setYear(eduStudentEnroll.getYear());
        queryVO.setClassify("2");
        EduOperationCacheDetailVO bmOption = eduSystemConfigIntegration.getEduOperationOne(queryVO);
        if (bmOption == null) {
            throw new AppException(4, "调剂申请尚未开始");
        } else {
            if (!bmOption.isFlag()) {
                if ("1".equalsIgnoreCase(bmOption.getType())) {
                    throw new AppException(4, "调剂申请尚未开始");
                } else if ("2".equalsIgnoreCase(bmOption.getType())) {
                    throw new AppException(4, "调剂申请已结束");
                }
            }
        }
        QueryWrapper<EduStudentTj> queryStudentWrapper = new QueryWrapper<>();
        queryStudentWrapper.lambda().eq(EduStudentTj::getStudentEnrollId, vo.getStudentEnrollId())
                .eq(EduStudentTj::getFromSchoolId, eduStudentEnroll.getSchoolId())
                .eq(EduStudentTj::getCurrentFlag, BoolEnum.TRUE.getType());
        EduStudentTj eduStudentCheck = eduStudentTjService.getOne(queryStudentWrapper, false);
        if (eduStudentCheck != null) {
            if (AuthStatusEnum.NODO.getType().equalsIgnoreCase(eduStudentCheck.getAuthStatus())) {
                throw new AppException(2, "请耐心等待审核");
            } else if (AuthStatusEnum.YES.getType().equalsIgnoreCase(eduStudentCheck.getAuthStatus())) {
                throw new AppException(3, "已完成调剂");
            }
        }
        QueryWrapper<EduSchoolTj> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(EduSchoolTj::getToSchoolName, EduSchoolTj::getToSchoolId).eq(EduSchoolTj::getFromSchoolId, eduStudentEnroll.getSchoolId())
                .eq(EduSchoolTj::getFromConfigName, eduStudentEnroll.getConfigName())
                .eq(EduSchoolTj::getFlag, BoolEnum.TRUE.getType())
                .eq(EduSchoolTj::getYear, eduStudentEnroll.getYear()).groupBy(EduSchoolTj::getToSchoolId, EduSchoolTj::getToSchoolName);
        List<EduSchoolTj> eduSchoolTjList = eduSchoolTjService.list(queryWrapper);
        if (CollectionUtils.isEmpty(eduSchoolTjList)) {
            return new ArrayList<>();
        }
        List<MyTjSchoolVO> retList = new ArrayList<>();
        for (EduSchoolTj eduSchoolTj : eduSchoolTjList) {
            MyTjSchoolVO myTjSchoolVO = new MyTjSchoolVO();
            myTjSchoolVO.setSchoolId(eduSchoolTj.getToSchoolId());
            myTjSchoolVO.setSchoolName(eduSchoolTj.getToSchoolName());
            retList.add(myTjSchoolVO);
        }
        return retList;
    }
}
